package com.linshidream.intrachat.simplenio.packet.handler;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2025/7/31 18:01
 *
 * @author linshidream
 * @version 1.0.0
 * @description
 */

public class LengthFieldMessageCodec implements MessageCodec {

    /**
     * 4 bytes表示消息长度（int）
     */
    private static final int LENGTH_HEADER_SIZE = 4;

    @Override
    public ByteBuffer encode(String msg) {
        // 协议格式：4kb数据长度（int） + 数据
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);

        ByteBuffer buffer = ByteBuffer.allocate(4 + bytes.length);
        buffer.putInt(bytes.length);
        buffer.put(bytes);

        buffer.flip();
        return buffer;
    }

    @Override
    public List<String> decode(ByteBuffer buffer) {
        List<String> messages = new ArrayList<>();
        buffer.flip();

        while (buffer.remaining() > LENGTH_HEADER_SIZE) {
            // 标记下当前的位置
            buffer.mark();
            // 获取到4kb(int)
            int len = buffer.getInt();
            if (buffer.remaining() < len) {
                buffer.reset();
                break;
            }

            // 每次读一定长度的数据。
            byte[] msgBytes = new byte[len];
            buffer.get(msgBytes);
            messages.add(new String(msgBytes, StandardCharsets.UTF_8));
        }

        // 保留未读 开启写模式
        buffer.compact();
        return messages;
    }
}
